package com.ob.core.util;

import com.ob.core.exception.ObException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;

import java.util.ArrayList;
import java.util.List;


/**
 * @author : xzzz
 */
public class BeanUtil extends BeanUtils {

    private static final Logger log = LoggerFactory.getLogger(BeanUtil.class);

    /**
     * 对象拷贝 (数据源为空返回空)
     * @param from 数据源
     * @param to 目标对象
     * @param <T> 范型
     * @return 数据源为空返回空
     */
    public static <T> T copyObject(Object from, Class<T> to) {
        try {
            if (null == from) {
                return null;
            }
            T dest;
            dest = to.newInstance();
            copyProperties(from , dest);
            return dest;
        } catch (InstantiationException | IllegalAccessException | BeansException e) {
            e.printStackTrace();
            throw new ObException("对象复制错误");
        }
    }

    /**
     * 拷贝集合
     * @param from 数据源
     * @param to 目标
     * @param <T> 范型
     * @return 数据源为空返回空
     */
    public static <T> List<T> copyList(List<?> from, Class<T> to) {
        List<T> dest = new ArrayList<>();
        from.forEach((Object e) -> {
            try {
                T toObject = to.newInstance();
                copyProperties(e, toObject);
                dest.add(toObject);
            } catch (Exception e1) {
                log.error("拷贝集合错误:" + e1);
            }
        });
        return dest;
    }
}
